// pages/addAddress/addAddress.js
const addressService = require('../../../../../api/addressService.js')
var QQMapWX = require('../../../../../libs/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    region: ['省', '市', '区'],
    name: '',
    phone: '',
    details: '',
    houseNumber: '',
    addressInfo: {},
    defaultColor: "#009f55",
    isDefault: false,
    detailedLabelShow: false,
    genders: [{ name: '先生', value: 'MALE', id: 0 }, { name: '女士', value: 'FEMALE', id: 1 }],
    labels: [{ name: '家', id: 0 }, { name: '公司', id: 1 }, { name: '学校', id: 2 }],
    currentLabel: -1,
    userGenders: -1,
    systemDetail: false,
    pageType: 'normal'
  },
  // 处理地址选择点击事件
  handleClick: function (e) {
    const that = this
    var index = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    if (type === 'gender') {
      if (that.data.userGenders !== index) {
        that.setData({
          userGenders: index
        })
      } else {
        that.setData({
          userGenders: -1
        })
      }
    } else if (type === 'label') {
      if (that.data.currentLabel !== index) {
        that.setData({
          currentLabel: index
        })
      } else {
        that.setData({
          currentLabel: -1
        })
      }
    }
  },
  // 删除地址
  doDeleteAddress: function () {
    const that = this
    var id = that.data.addressInfo.id
    if (id && id != '') {
      wx.showModal({
        title: '提示',
        content: '请确认要删除地址？',
        success: function (res) {
          if (res.confirm) {
            addressService.removeById(id).then(res => {
              console.log(res)
              wx.showToast({
                title: "删除成功~",
                icon: 'none',
                duration: 2000
              })
              try {
                var value = wx.getStorageSync('wj_chooseAddressInfo')
                if (value) {
                  if (value.id === id) {
                    wx.removeStorageSync('wj_chooseAddressInfo')
                  }
                }
              } catch (e) {
                // Do something when catch error
              }
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1
                })
              }, 2000);
            }).catch(e => {
              wx.showToast({
                title: "删除失败~",
                icon: 'none',
                duration: 2000
              })
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {

    }
  },
  // 搜索框点击事件,输入框聚焦
  handleFocus: function (e) {
    this.setData({
      detailedLabelShow: true
    })
  },
  // 搜索框失去焦点处理
  handleBlur: function (e) {
    this.setData({
      detailedLabelShow: false
    })
  },
  bindRegionChange: function (e) {
    let that = this
    that.setData({
      region: e.detail.value
    })
  },
  // 处理详细地址输入
  handleDetails: function (e) {
    this.setData({
      details: e.detail.value
    })
  },
  // 处理门牌号输入
  handleHouseNumber: function (e) {
    console.log(e.detail)
    if (e.detail.cursor < 40) {
      this.setData({
        houseNumber: e.detail.value
      })
    } else if (e.detail.cursor === 40) {
      this.setData({
        houseNumber: e.detail.value
      })
      wx.showToast({
        title: '详细地址最大不能超50个字符哦~',
        icon: 'none',
        duration: 2000
      })
    } else {

    }
  },
  // 处理姓名输入
  handleName: function (e) {
    if (e.detail.cursor < 10) {
      this.setData({
        name: e.detail.value
      })
    } else if (e.detail.cursor === 10) {
      this.setData({
        name: e.detail.value
      })
      wx.showToast({
        title: '联系人昵称最大不能超10个字符哦~',
        icon: 'none',
        duration: 2000
      })
    } else {

    }
  },
  // 处理手机号输入
  handlePhone: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },
  // 处理默认地址
  handleDefault: function (e) {
    this.setData({
      isDefault: e.detail.value
    })
  },
  handleSave: function (e) {
    console.log(e.detail.value)
    var self = this;
    let reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
    if (e.detail.value.region[0] == '省') {
      wx.showToast({
        title: "请选择省市区",
        icon: 'none',
        duration: 2000
      })
    } else if (!e.detail.value.details) {
      wx.showToast({
        title: "请填写详细地址",
        icon: 'none',
        duration: 2000
      })
    } else if (!e.detail.value.houseNumber) {
      wx.showToast({
        title: "请输入门牌号",
        icon: 'none',
        duration: 2000
      })
    } else if (!e.detail.value.name) {
      wx.showToast({
        title: "请输入联系人姓名",
        icon: 'none',
        duration: 2000
      })
    } else if (!e.detail.value.phone) {
      wx.showToast({
        title: "请输入联系方式",
        icon: 'none',
        duration: 2000
      })
    } else if (reg.test(e.detail.value.phone) === false) {
      wx.showToast({
        title: "请输入正确的联系方式",
        icon: 'none',
        duration: 2000
      })
    } else {
      console.log(e.detail.value)
      try {
        var value = wx.getStorageSync('wj_member')
        if (value) {
          qqmapsdk.geocoder({
            address: e.detail.value.region[0] + e.detail.value.region[1] + e.detail.value.region[2] + e.detail.value.details + e.detail.value.houseNumber,
            success: function (res) {
              console.log(res);
              if (self.options.doEditAddress === "edit") {
                // 修改地址
                let postData = {
                  id: self.data.addressInfo.id,
                  userId: value.id,
                  province: e.detail.value.region[0],
                  city: e.detail.value.region[1],
                  county: e.detail.value.region[2],
                  detailedAddress: e.detail.value.details,
                  houseNum: e.detail.value.houseNumber,
                  contactsMobile: e.detail.value.phone,
                  contacts: e.detail.value.name,
                  defaultAddress: e.detail.value.isDefault,
                  latitude: res.result.location.lat,
                  longitude: res.result.location.lng
                }
                if (self.data.userGenders === -1) {
                  postData = {
                    ...postData,
                    gender: 'UNKNOWN'
                  }
                } else if (self.data.userGenders === 0) {
                  postData = {
                    ...postData,
                    gender: 'MALE'
                  }
                } else if (self.data.userGenders === 1) {
                  postData = {
                    ...postData,
                    gender: 'FEMALE'
                  }
                }
                const tab = self.data.currentLabel
                const labels = self.data.labels
                if (tab !== -1) {
                  labels.forEach(item => {
                    if (item.id === tab) {
                      postData = {
                        ...postData,
                        label: item.name
                      }
                    }
                  })
                } else {
                  postData = {
                    ...postData,
                    label: ''
                  }
                }
                addressService.update(postData).then(res => {
                  wx.navigateBack({
                    delta: 1
                  })
                }).catch(err => {
                  wx.showToast({
                    title: err.message,
                    icon: 'none',
                    duration: 2000
                  })
                })
              } else {
                // 新增地址
                let postData = {
                  userId: value.id,
                  province: e.detail.value.region[0],
                  city: e.detail.value.region[1],
                  county: e.detail.value.region[2],
                  detailedAddress: e.detail.value.details,
                  houseNum: e.detail.value.houseNumber,
                  contactsMobile: e.detail.value.phone,
                  contacts: e.detail.value.name,
                  defaultAddress: e.detail.value.isDefault,
                  latitude: res.result.location.lat,
                  longitude: res.result.location.lng
                }
                if (self.data.userGenders === -1) {
                  postData = {
                    ...postData,
                    gender: 'UNKNOWN'
                  }
                } else if (self.data.userGenders === 0) {
                  postData = {
                    ...postData,
                    gender: 'MALE'
                  }
                } else if (self.data.userGenders === 1) {
                  postData = {
                    ...postData,
                    gender: 'FEMALE'
                  }
                }
                const tab = self.data.currentLabel
                const labels = self.data.labels
                if (tab !== -1) {
                  labels.forEach(item => {
                    if (item.id === tab) {
                      postData = {
                        ...postData,
                        label: item.name
                      }
                    }
                  })
                } else {
                  postData = {
                    ...postData,
                    label: ''
                  }
                }
                addressService.create(postData).then(res => {
                  wx.navigateBack({
                    delta: 1
                  })
                }).catch(err => {
                  wx.showToast({
                    title: err.message,
                    icon: 'none',
                    duration: 2000
                  })
                })
              }
            },
            fail: function (res) {
              console.log(res);
            }
          });

        } else {
          wx.showToast({
            title: '您还不是会员，请先绑定手机号码成为会员',
            icon: 'none',
            duration: 2000
          })
        }
      } catch (e) {
        // Do something when catch error
      }
    }
  },
  // 选择地址
  chooseAddress: function () {
    const that = this
    const region = that.data.region
    console.log(region)
    wx.chooseLocation({
      success: function (res) {
        // success
        console.log(res, "location")
        var regex = /^(北京市|天津市|重庆市|上海市|香港特别行政区|澳门特别行政区)/;
        var province = [];
        var addressBean = {
          province: null,
          country: null,
          city: null,
          address: null
        };
        var addressName = res.name
        function regexAddressBean(address, addressBean) {
          regex = /^(.*?[市]|.*?地区|.*?特别行政区|.*?盟|.*?自治州)(.*?[市区县旗])(.*?)$/g;
          var addxress = regex.exec(address);
          console.log(addxress);
          addressBean.city = addxress[1];
          addressBean.country = addxress[2];
          addressBean.address = addxress[3];
        }
        if (!(province = regex.exec(res.address))) {
          regex = /^(.*?(省|自治区))(.*?)$/;
          province = regex.exec(res.address);
          if (province) {
            addressBean.province = province[1];
            regexAddressBean(province[3], addressBean);
          } else {
            var regexe = /^(.*?)\((.+?)\)$/g;
            var data = regexe.exec(res.address)
            console.log(data)
            console.log(region)
            var latitude = res.latitude
            var longitude = res.longitude
            qqmapsdk.reverseGeocoder({
              location: {
                latitude: latitude,
                longitude: longitude
              },
              success: function (res) {
                console.log(res)
                addressBean.province = res.result.address_component.province
                addressBean.city = res.result.address_component.city;
                addressBean.country = res.result.address_component.district;
                that.setData({
                  region: [
                    addressBean.province,
                    addressBean.city,
                    addressBean.country
                  ]
                })
              },
              fail: function (res) {
                console.log(res);
              }
            })
            addressBean.address = data[2];
            addressName = data[1];
          }
        } else {
          addressBean.province = province[1];
          if (res.poiid && res.poiid === 'City') {
            // 处理IOS第一行数据返回有错
            var regexe = /^(.*?)\((.+?)\)$/g;
            var data = regexe.exec(res.name)
            console.log(data)
            var latitude = res.latitude
            var longitude = res.longitude
            qqmapsdk.reverseGeocoder({
              location: {
                latitude: latitude,
                longitude: longitude
              },
              success: function (res) {
                console.log(res)
                addressBean.province = res.result.address_component.province
                addressBean.city = res.result.address_component.city;
                addressBean.country = res.result.address_component.district;
                that.setData({
                  region: [
                    addressBean.province,
                    addressBean.city,
                    addressBean.country
                  ]
                })
              },
              fail: function (res) {
                console.log(res);
              }
            })
            addressBean.address = data[2];
            addressName = data[1];
          } else {
            regexAddressBean(res.address, addressBean);
          }
        }
        console.log(addressBean)
        if (addressBean.address !== '') {
          that.setData({
            detailedLabelShow: true
          })
        }
        that.setData({
          details: addressName,
          houseNumber: addressBean.address,
          region: [
            addressBean.province,
            addressBean.city,
            addressBean.country
          ]
        })
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    var phone = wx.getSystemInfoSync();  //调用方法获取机型
    var detail = null;
    if (phone.platform == 'ios') {
      detail = true;
    } else if (phone.platform == 'android') {
      detail = false;
    }
    this.setData({
      systemDetail: detail
    })
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'AD5BZ-CHCKS-64OOD-6G6TX-BSOA6-IFF3V'
    });
    var self = this;
    if (options.doEditAddress === "edit") {
      wx.setNavigationBarTitle({
        title: '修改收货地址'
      })
      self.setData({
        pageType: 'edit'
      })
      try {
        var startAddress = wx.getStorageSync('wj_editAddress')
        var addressId = startAddress.id
        addressService.query().then(res => {
          res.forEach((item) => {
            if (item.id === addressId) {
              self.data.addressInfo = item
              let address = self.data.addressInfo
              this.setData({
                region: [address.province, address.city, address.county],
                name: address.contacts,
                phone: address.contactsMobile,
                details: address.detailedAddress,
                houseNumber: address.houseNum,
                isDefault: address.defaultAddress,
              })
              if (item.gender === "UNKNOWN") {
                this.setData({
                  userGenders: -1
                })
              } else if (item.gender === "MALE") {
                this.setData({
                  userGenders: 0
                })
              } else if (item.gender === "FEMALE") {
                this.setData({
                  userGenders: 1
                })
              }
              let label = item.label
              const labels = self.data.labels
              labels.forEach(item => {
                if (item.name == label) {
                  self.setData({
                    currentLabel: item.id
                  })
                }
              })
            }
          })
        }).catch(err => {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        })

      } catch (e) { }
    } else {
      try {
        var locationInfo = wx.getStorageSync('wj_locationInfo')
        if (locationInfo) {
          // Do something with return value
          console.log(locationInfo)
          self.setData({
            region: [
              locationInfo.ad_info.province,
              locationInfo.ad_info.city,
              locationInfo.ad_info.district,
            ],
            details: locationInfo.title,
            houseNumber: locationInfo.address,
          })
          wx.removeStorageSync('wj_locationInfo')
          this.getUserAddress()
        } else {
          this.getUserAddress()
        }
      } catch (e) {
        // Do something when catch error
      }
    }
  },
  getUserAddress: function () {
    const that = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res)
        var latitude = res.latitude
        var longitude = res.longitude
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: latitude,
            longitude: longitude
          },
          success: function (res) {
            console.log(res)
            that.setData({
              region: [
                res.result.address_component.province,
                res.result.address_component.city,
                res.result.address_component.district,
              ]
            })
          },
          fail: function (res) {
            console.log(res);
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})